package com.np.library1;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

public class BitmapUtil {

    /**
     * 随机生成 Bitmap
     *
     * @return
     */
    public static Bitmap generateBitmap() {
        long i = new Random().nextInt(900000000) + 100000000;
        return stringToBitmap(String.valueOf(i));
    }

    /**
     * 由字符串生成 Bitmap 图片
     *
     * @param text
     * @return
     */
    public static Bitmap stringToBitmap(String text) {

        int textSize = 10;
        int width = 100;
        int height = 100;
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        // 设置背景颜色
        canvas.drawColor(Color.WHITE);

        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(textSize);

        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);

        // 计算文本的宽度和高度
        float x = (bitmap.getWidth() - bounds.width()) / 2f;
        float y = (bitmap.getHeight() - bounds.height()) / 2f;

        // 在画布上绘制文本
        canvas.drawText(text, x, y, paint);

        return bitmap;
    }

    /**
     * 图片文件转 Bitmap
     * @param file
     * @return
     */
    public static Bitmap imageToBitmap(String file) {
        return BitmapFactory.decodeFile(file);
    }

    /**
     * Bitmap 转 二进制数组
     *
     * @param bitmap
     * @return
     */
    private byte[] bitMapToByteArray(Bitmap bitmap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }
}
